<template>
  <div>

    <!-- 模态框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <el-form :model="form1" :rules="rules" ref="form1">
        <el-form-item label="原密码" :label-width="'120px'" prop="oldPwd" class="demo-ruleForm">
          <el-input type="password" v-model="form1.oldPwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item  label="新密码" :label-width="'120px'" prop="newPwd">
          <el-input type="password" v-model="form1.newPwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item  label="确认新密码" :label-width="'120px'" prop="checkPwd">
          <el-input type="password" v-model="form1.checkPwd" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm('form1')">确 定</el-button>
      </span>
    </el-dialog>

    <el-row :gutter="24">
      <el-col :span="9"
        ><div class='grid-content'>
          <el-row>
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>个人信息</span>
              </div>
              <div style="text-align: center">
                <!--图片上传-->
                <el-upload
                        class="avatar-uploader"
                        :action="url"
                        name="file"
                        :auto-upload='true'
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img style="width: 100px; height: 100px" v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
              <ul class="user-info">
                <li><div style="height: 100%"> 登录账号<div class="user-right">{{userName}}</div></div></li>
                <li> 用户昵称 <div class="user-right">{{loginName}}</div></li>
                <!-- <li> 所属部门 <div class="user-right">{{deptName}}</div></li> -->
                <li> 手机号码 <div class="user-right">{{phonenumber}}</div></li>
                <li> 用户邮箱 <div class="user-right">{{email}}</div></li>
                <li>
                  安全设置
                  <div class="user-right">
                    <a href="#" @click="updatePassword">修改密码</a>
                  </div>
                </li>
              </ul>
              
            </el-card>
          </el-row>
        </div></el-col
      >
      <el-col :span="15">
        <!--    用户资料    -->
        <el-card class="box-card2">
          <el-tabs v-model="activeName">
            <!-- <el-tab-pane label="用户资料" name="first">
              <el-form ref="form" :model="form"  style="margin-top: 10px;" size="small" label-width="65px">
                <el-form-item label="昵称" prop="loginName">
                  <el-input v-model="form.loginName" style="width: 35%" />
                  <span style="color: #C0C0C0;margin-left: 10px;">用户昵称不作为登录使用</span>
                </el-form-item>
                <el-form-item label="手机号" prop="phonenumber">
                  <el-input v-model="form.phonenumber" style="width: 35%;" />
                  <span style="color: #C0C0C0;margin-left: 10px;">*****手机号码请仔细核对</span>
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="form.sex" style="width: 178px">
                    <el-radio label="0">男</el-radio>
                    <el-radio label="1">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="">
                  <el-button size="mini" type="primary" @click="doSubmit">保存配置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane> -->
            <!--    操作日志    -->
            <el-tab-pane label="操作日志" name="first">
              <el-table :data="operData" style="width: 100%;">
                <el-table-column
                  prop="businessType"
                  label="行为">
                  <template scope="scope">
                    <span v-if="scope.row.businessType==3" style="color:red;">删除</span>
                    <span v-else-if="scope.row.businessType==2" style="color:red;">修改</span>
                    <span v-else-if="scope.row.businessType==1" style="color:red;">新增</span>
                    <span v-else style="color:red;">其他</span>
                  </template>
                </el-table-column>
                <el-table-column prop="operIp" label="IP" />
                <el-table-column prop="operUrl" label="请求URL" width="120">
                </el-table-column>
                <el-table-column
                  align="right"
                  width="180"
                >
                  <template slot="header">
                    <div style="display:inline-block;float: right;cursor: pointer">创建日期<i class="el-icon-refresh" style="margin-left: 40px" /></div>
                  </template>
                  <template slot-scope="scope">
                    <span>{{ scope.row.operTime }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <!--分页组件-->
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange2"
                :current-page="currentPage"
                :page-sizes="[2, 3, 5, 10, 20, 100, 200, 300, 400]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
              >
              </el-pagination>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>
<script>

export default {
  data() {
    var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          this.$http({
            method: "get",
            url: "/api/sso/userLogin/authUser?userName="+localStorage.getItem("userName")+"&passWord="+value
          }).then((response) => {
            console.log(response)
            if(response.data.code==2000){
              callback();
            } else {
              callback(new Error('原密码错误！'));
            }
          });
        }
    };
    var validatePass2 = (rule, value, callback) => {
        if (this.form1.checkPwd === '') {
          callback(new Error('请再次输入密码'));
        } else if (this.form1.checkPwd !== this.form1.newPwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
    };
    return{
      url:this.$base_url+"/api/cs/commonOSS/upload?accessToken="+localStorage.getItem("token"),
      userName:'',
      loginName:'',
      // deptName:'',
      phonenumber:'',
      email:'',
      form: {userId:localStorage.getItem("userId")},
      tableData: [],
      currentPage: 1,
      total: 100,
      activeName:'first',
      pageSize: 5,
      operData:[],
      imageUrl:'',
      // headers: {accessToken : sessionStorage.getItem('accessToken')},
      form1:{oldPwd:'',newPwd:'',checkPwd:''},
      dialogVisible: false,
      rules: {
        oldPwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' },
        ],
        newPwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,30}$/, message: '密码为数字，小写字母，大写字母，特殊符号 至少包含三种，长度为 8 - 30位，密码不能包含 用户名，公司名称(lidian), 公司域名(rekoon) （判断的时候不区分大小写)' }

        ],
        checkPwd: [
          { validator: validatePass2, trigger: 'blur' }
        ],
      },
    }
  },
  // 初始化数据  mounted()
  created: function () {
    this.imageUrl=localStorage.getItem("avatar")
    this.userName=localStorage.getItem("userName")
    this.loginName=localStorage.getItem("loginName")
    // this.deptName=localStorage.getItem("deptName")
    this.phonenumber=localStorage.getItem("phonenumber")
    this.email=localStorage.getItem("email")
    this.pageSize=4;
    this.currentPage=1;
    // this.userId=localStorage.getItem("userId")
    this.loadData();
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //消息提示
    // open1() {
    //   this.$message({
    //     message: '成功！',
    //     type: 'success'
    //   });
    // },
    // open2() {
    //   this.$message.error('失败！！！');
    // },
    loadData() {
      var _this = this;
      //操作日志
      this.$http({
        method: "post",
        url: "/api/cs/operLog/queryAll?pageNo="+this.currentPage+"&pageSize="+this.pageSize,
        data: {operName:this.userName},
      }).then((response) => {
        //console.log(JSON.stringify(response.data)+"...111..")
        _this.operData = response.data.data.list;
        _this.total = response.data.data.total;
        // alert(JSON.stringify( response.data.data))
      });
    },
    //分页 每页数量变化时处理
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.loadData();
    },
    //分页 第几页变化时处理
    handleCurrentChange2(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadData();
    },
    //提交资料更改
    doSubmit() {
      this.form={loginName:this.form.loginName,phonenumber:this.form.phonenumber,sex:this.form.sex,userId:this.form.userId}
      this.$http.post(url, this.form)
        .then(function (response) {
            console.log(response);
            //提交成功
            if(response.data.code==2000){
                //关闭弹出框
                _this.dialogFormVisible=false;
                //提示更新成功
                _this.$message({
                  //  message: '恭喜你，这是一条成功消息',
                    message: response.data.message,
                    type: 'success'
                });
                //重新加载数据
                _this.loadData();
            }else {
                _this.$message.error(response.data.message);
            }
        })
        .catch(function (error) {
            _this.$message.error('错了哦，这是一条错误消息');
        });
    },
    //修改密码
    updatePassword(){
      this.form1={oldPwd:'',newPwd:'',checkPwd:''};
      this.dialogVisible = true;
    },
    //提交更改密码
    confirm(formName){
      this.$refs[formName].validate((valid) => {
        // password
          if (valid) {
            let data={password:this.form1.newPwd,userId:localStorage.getItem("userId")};
            // this.$http({
            //   method: "post",
            //   url: "/cs/user/update",
            //   data: myPassword,
            // }).then((response) => {
            //   if(response.data.returnCode=='2000'){
            //     this.open1();
            //     //this.$set(this.tableData, this.index, this.form1);
            //     this.loadData();
            //   } else {
            //     this.open2();
            //   }
            // });
            var _this=this;
            this.$http.post("/api/cs/user/update", data)
                .then(function (response) {
                    console.log(response);
                    //提交成功
                    if(response.data.code==2000){
                        //关闭弹出框
                        _this.dialogFormVisible=false;
                        //提示更新成功
                        _this.$message({
                          //  message: '恭喜你，这是一条成功消息',
                            message: response.data.message,
                            type: 'success'
                        });
                        //重新加载数据
                        // _this.loadData();
                        this.dialogVisible = false;
                    }else {
                        _this.$message.error(response.data.message);
                    }
                })
                .catch(function (error) {
                    _this.$message.error('错了哦，这是一条错误消息');
                });
          } else {
            return false;
          }
        });
    },
    //文件上传
     //图片上传成功后
    handleAvatarSuccess:function(res, file) {
        //图片回显
        this.imageUrl = URL.createObjectURL(file.raw);
    //   alert(file.response);
      // alert(JSON.stringify(file.response));
      
        this.form.avatar=file.response.ossFileUrlBoot;
        var _this=this;
        alert(JSON.stringify(this.form))
        this.$http.post("/api/cs/user/update",this.form).then(function (response) {
                            console.log(response);
                            //提交成功
                            if(response.data.code==2000){
                                //关闭弹出框
                                // _this.dialogFormVisible=false;
                                // _this.dialogFormVisible1=false;
                                //提示更新成功
                                localStorage.setItem("avatar",_this.form.avatar);
                                _this.$message({
                                  //  message: '恭喜你，这是一条成功消息',
                                    message: response.data.message,
                                    type: 'success'
                                });
                                //重新加载数据
                                // _this.loadData();
                                // _this.$router.push('/index');
                            }else {
                                _this.$message.error(response.data.message);
                            }
                        })
                        .catch(function (error) {
                            _this.$message.error('错了哦，这是一条错误消息');
        });

        // this.form.fileName=file.response.oldFileName;
        // this.form.filePath=file.response.newFilePath;
    },
    //上传前图片类型和大小判断
    beforeAvatarUpload:function(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        /* if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
        }*/
        if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return  isLt2M;
    },
  },
};
</script>
<style scoped >

.row-bg {
  padding: 10px 0;
  /* background-color: ; */
}
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 400px;
  }
  .box-card2 {
    width: 600px;
  }
  
    .avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
  }
  .user-info {
    padding-left: 0;
    list-style: none;
  }
  .user-info li{
    border-bottom: 1px solid #F0F3F4;
      padding: 11px 0;
      font-size: 13px;
      text-align: left;
  }
  .user-info .user-right {
      float: right;
    } a{
      color: #317EF3;
    }

</style>